package com.laicunba.ext.web.filter;

import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import com.laicunba.util.SessionUtil;
import com.laicunba.util.StringUtil;

public class CacheResponseWrapper extends HttpServletResponseWrapper {

	private CharArrayWriter bufferWriter = new CharArrayWriter();

	class CopyPrintWriter extends PrintWriter {

		public CopyPrintWriter(Writer out) {
			super(out);
		}

		@Override
		public void write(char[] buf, int off, int len) {
			super.write(buf, off, len);
			bufferWriter.write(buf, off, len);
		}

		@Override
		public void write(String s, int off, int len) {
			super.write(s, off, len);
			bufferWriter.write(s, off, len);
		}

		@Override
		public void write(int c) {
			super.write(c);
			bufferWriter.write(c);
		}

		@Override
		public void write(String s) {
			super.write(s);
			try {
				bufferWriter.write(s);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void write(char[] buf) {
			super.write(buf);
			try {
				bufferWriter.write(buf);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public CacheResponseWrapper(HttpServletResponse httpServletResponse) {
		super(httpServletResponse);

	}

	@Override
	public PrintWriter getWriter() throws IOException {
		if (StringUtil.isEmpty(SessionUtil.RESPONSE_CACHE_KEY.get())) {
			return super.getWriter();
		}
		return new CopyPrintWriter(super.getWriter());
	}

	public String getResponseString() {
		return bufferWriter.toString();

	}

}
